<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-col :span="8">
        <el-input class=" ww-border" placeholder="请输入内容" v-model="searchName">
          <el-button @click="search" class="search-bg" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </el-col>
      <el-col :span="16">
        <el-button class="filter-item btn-ww pull-right" style="margin-right: 10px;" @click="handleCreate" type="primary"
                   icon="el-icon-edit">添加
        </el-button>
      </el-col>

    </div>
    <el-table class="table-border color-none" border :key='tableKey' :data="list" v-loading="listLoading"
              element-loading-text="正在努力加载中。。。" fit

              highlight-current-row :row-class-name="tableRowClassName"
              style="width: 100%; margin-top: 15px">
      <el-table-column align="center" label="NO." width="65" type="index">
      </el-table-column>
      <el-table-column min-width="150px" label="用户名" align="center">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150px" label="手机号" align="center">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.username ||scope.row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="320" class-name="small-padding">
        <template slot-scope="scope">
          <el-button class="btn-ww" icon="el-icon-edit-outline" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button class="btn-ww" type="primary" size="mini" @click="resetPass(scope.row)">重置密码</el-button>
          <el-button class="btn-ww" icon="el-icon-delete" v-if="scope.row.status!='deleted'" @click="handleModifyStatus(scope.row,'deleted')"
                     size="mini" type="danger"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.pageNumber"
                     :page-size="listQuery.pageSize"
                     layout="prev, pager, next"
                     :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px"
               style='width: 400px; margin-left:50px;'>
        <el-form-item label="姓名" prop="type">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="type" v-if="dialogStatus !== 'update'">
          <el-input v-model="temp.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="type">
          密码为手机号码后6位
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'重置密码'" :visible.sync="dialogPassVisible" width="586">
      <el-form :rules="passRules" ref="passForm" :model="temp" label-position="left" label-width="70px"
               style='width: 400px; margin-left:50px;'>
        <el-form-item label="手机号" prop="type">
          <el-input disabled="disabled" v-model="passForm.username"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input name="captcha" type="text" v-model="passForm.captcha" autoComplete="on" placeholder="请输入验证码"/>
          <timer class="timer" :start='start' @countDown='start=false' @click.native='sendUserCode'></timer>
        </el-form-item>
        <el-form-item label="新密码" prop="type">
          <el-input v-model="passForm.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPassVisible = false">取 消</el-button>
        <el-button type="primary" @click="confimReset">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchList, addUser,addSubUser, delUser, editUser, resetPass} from '../../../api/user'
  import {validatMobile} from '../../../utils/validate'
  import timer from '../../register/timer.vue'
  import {getCode} from '../../../api/register'
  import {getLoginUser} from '../../../utils/auth'

  export default {
    name: 'complexTable',
    components: {
      timer
    },
    data() {
      const valMobile = (rule, value, callback) => {
        if (!validatMobile(value)) {
          callback(new Error('请输入正确的用户名'))
        } else {
          callback()
        }
      }
      const validatePass = (rule, value, callback) => {
        if (value.length < 5) {
          callback(new Error('密码不能小于5位'))
        } else {
          callback()
        }
      }
      return {
        tableKey: 0,
        searchName: '',
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          pageNumber: 1,
          pageSize: 10,
          authority: 'ROLE_USER'
        },
        start: false,
        importanceOptions: [1, 2, 3],
        sortOptions: [{label: '按ID升序列', key: '+id'}, {label: '按ID降序', key: '-id'}],
        showAuditor: false,
        temp: {
          authority: 'ROLE_USER',
          captcha: '',
          companyId: localStorage.getItem('companyId'),
          mobile: '',
          name: '',
          password: ''
        },
        passForm: {
          username: '',
          captcha: '654321',
          password: ''
        },
        dialogFormVisible: false,
        dialogPassVisible: false,
        dialogStatus: '',
        textMap:
          {
            update: '编辑',
            create:
              '创建'
          },
        dialogPvVisible: false,
        visible2: false,
        rules: {
          username: [{required: true, message: '手机号必填', trigger: 'blur', validator: valMobile}]
        },
        passRules: {
          password: [{required: true, message: '密码必填', trigger: 'blur', validator: validatePass}]
        }
      }
    },
    filters: {},
    created() {
      this.getList()
    },
    methods: {
      search() {
        // do search
      },
      sendCode() {
        this.getMsgCode(this.temp.mobile)
      },
      sendUserCode() {
        this.getMsgCode(this.passForm.username)
      },
      getMsgCode(mobile) {
        if (mobile.length !== 11) {
          this.$message({
            message: '请输入手机号',
            type: 'error'
          })
          return
        }
        // 前面发送ajax请求成功之后调用this.start = true开始短信倒计时
        this.start = true
        getCode(mobile).then(() => {
          this.loading = false
        }).catch(() => {
          this.$message({
            message: '获取验证码失败，请重新尝试！',
            type: 'error'
          })
          this.loading = false
        })
      },
      getList() {
        this.listLoading = true
        this.total = 0
        this.listLoading = false
        const that = this
        fetchList(this.listQuery).then(response => {
          that.list = response.data.content
          that.total = response.data.totalElements || 0
          that.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNumber = val
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$confirm('是否删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUser(row.username || row.mobile).then(response => {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        row.status = status
      },
      resetPass(row) {
        this.dialogPassVisible = true
        this.passForm.username = row.username
        this.passForm.captcha = ''
        this.passForm.password = ''
        this.$nextTick(() => {
          this.$refs['passForm'].clearValidate()
        })
      },
      confimReset() {
        this.$refs.passForm.validate(valid => {
          if (valid) {
            resetPass(this.passForm).then(() => {
              this.dialogPassVisible = !this.dialogPassVisible
              this.$message('修改成功！')
            }).catch(() => {
              this.$message('重置密码失败！')
              console.log('重置密码失败！')
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetTemp() {
        this.temp = {
          name: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2 === 0) {
          return 'warning-row'
        }
        return ''
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.authority = 'ROLE_USER'
            this.temp.companyId = localStorage.getItem('companyId')
            addSubUser(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            editUser(tempData).then(() => {
              this.dialogFormVisible = false
              this.list.forEach((val) => {
                if (val.username === tempData.username) {
                  val.name = tempData.name
                  return
                }
              })
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      }
    }
  }
</script>
<style>
  .timer {
    top: 0px;
    right: 0px;
    bottom: 0px;
    position: absolute;
  }

</style>
